<template>
  <div class="app-container">
    <div class="openSearch" @click="container=!container">
      <span>搜索/筛选借款</span>
      <span :class="{opencolor:container}">[{{container?"隐藏":"展开"}}]</span>
    </div>
    <div class="filter-container" v-if="container">
      <el-row style="padding-bottom:10px;">
        <span>项目名称</span>
        <el-input
          @keyup.enter.native="handleFilter"
          style="width: 200px;"
          class="filter-item"
          size="mini"
          placeholder="项目名称"
          v-model="params['projectName']"
        ></el-input>
      </el-row>
      <el-row>
        <span>状态</span>
        <el-select v-model="params['status']" clearable placeholder="状态" size="small">
          <el-option
            v-for="(item,index) in checkStatusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-row>
      <el-row style="padding-top:10px">
        <el-button
          class="filter-item"
          type="primary"
          v-waves
          size="mini"
          icon="el-icon-search"
          @click="handleFilter"
        >搜索</el-button>
      </el-row>
    </div>

    <el-table
      :data="list"
      :height="tableHeight"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%;height:700px;"
    >
      <el-table-column prop="id" align="center" label="Id" width="80">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="projectName" align="center" label="项目名称" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.projectName}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="projectType" align="center" label="项目类型" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.projectType | projectFilter}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="totalAmount" align="center" label="项目总金额" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.totalAmount}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="availableAmount " align="center" label="剩余有效金额" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.availableAmount }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column prop="checkRemark" align="center" label="审核备注" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.checkRemark}}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="minLimitAmount" align="center" label="最低投资额度" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.minLimitAmount}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="maxLimitAmount" align="center" label="最高限额" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.maxLimitAmount}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="状态" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusTypes}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="investMonth" align="center" label="投资期限(月)" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.investMonth}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="transferFlag" align="center" label="是否可转让" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.transferFlag | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" align="center" label="发布时间" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.createTime | parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="220"
        class-name="small-padding"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="editRow(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDetail(scope.row)">详情</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10,20,30,50]"
        :page-size="params.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible">
      <el-form
        class="dialog-form"
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="110px"
      >
        <el-tabs type="border-card">
          <el-tab-pane label="基本信息">
            <el-row>
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="temp.projectName" placeholder="项目名称" style="width:300px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目类型" prop="projectType">
                  <el-select v-model="temp.projectType" placeholder="请选择">
                    <el-option
                      v-for="(item,value) in projectFilter"
                      :value="value+1"
                      :key="value"
                      :label="item.title"
                    >{{item.title}}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="项目总金额" prop="totalAmount">
                  <el-input v-model="temp.totalAmount" placeholder="项目总金额" style="width:300px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最低投资额度" prop="minLimitAmount">
                  <el-input v-model="temp.minLimitAmount" placeholder="最低投资额度" style="width:300px;">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="最高限额" prop="maxLimitAmount">
                  <el-input v-model="temp.maxLimitAmount" placeholder="最高限额" style="width:300px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="投资期限(月)" prop="investMonth">
                  <el-select v-model="temp.investMonth" placeholder="请选择">
                    <el-option
                      v-for="(item,value) in investMonthItem"
                      :key="value"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="预计收益" prop="planIncomeRate">
                  <el-input
                    v-model.number="temp.planIncomeRate"
                    placeholder="预计收益"
                    style="width:300px;"
                  >
                    <template slot="append">%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="投资总额" prop="totalInvestAmount">
                  <el-input
                    v-model="temp.totalInvestAmount"
                    placeholder="投资总额"
                    style="width:300px;"
                  >
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="募集期(天)" prop="collectDays">
                  <el-input-number v-model="temp.collectDays" :min="1" label="募集期"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="项目标签" prop="projectTag">
                  <el-input v-model="temp.projectTag" placeholder="项目标签" style="width:300px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="管理费类型" prop="manageFeeType">
                  <el-radio-group v-model="temp.manageFeeType">
                    <div style="display:flex;">
                      <div>
                        <el-radio
                          v-for="(item,value) in manageFeeTypeItems"
                          :key="value"
                          :label="value"
                          :value="value"
                          style="display:flex;"
                        >{{item.title}}</el-radio>
                      </div>
                      <el-input
                        v-model="temp.manageFeeRate"
                        v-if="temp.manageFeeType === 0"
                        placeholder="管理费比例"
                        style="width:300px;"
                      ></el-input>
                      <el-input
                        v-model="temp.manageFeeAmount"
                        v-if="temp.manageFeeType === 1"
                        placeholder="固定管理费金额"
                        style="width:300px;"
                      ></el-input>
                    </div>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="是否可转让" prop="transferFlag">
                  <el-radio-group v-model="temp.transferFlag">
                    <el-radio
                      v-for="(item,value) in statusFilter"
                      :key="value"
                      :label="value"
                      :value="value"
                    >{{item}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="推荐理由">
            <div>
              <h4>推荐理由</h4>
            </div>
            <el-form-item v-for="(item, index) in recoValidateForm" :key="index" class="item">
              <el-form-item label="图标" prop="recoIcon">
                <div style="display:flex;">
                  <el-input v-model="item.recoIcon" placeholder="标题" style="width:300px;"></el-input>
                  <el-form-item style="padding-left:200px;">
                    <el-button @click.prevent="recoRemoveDomain(item)">删除</el-button>
                  </el-form-item>
                </div>
              </el-form-item>
              <el-form-item label="标题" prop="recoTitle">
                <el-input v-model="item.recoTitle" placeholder="标题" style="width:300px;"></el-input>
              </el-form-item>
              <el-form-item label="说明" prop="recoDesc">
                <el-input
                  v-model="item.recoDesc"
                  type="textarea"
                  rows="5"
                  placeholder="说明"
                  style="width:500px;"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item style="padding-left:300px;">
                <el-button @click.prevent="recoRemoveDomain(item)">删除</el-button>
              </el-form-item>-->
            </el-form-item>
            <div class="btn">
              <el-button type="primary" size="mini" @click="recoAddDomain" class="jixuBtn">+继续添加</el-button>
            </div>
            <div class="quill-wrap" style="height:350px;width:100%;margin-top:50px;">
              <quill-editor
                style="height:300px;"
                v-model="temp.recommendDesc "
                ref="myQuillEditor"
                :options="editorOption"
              ></quill-editor>
            </div>
          </el-tab-pane>

          <el-tab-pane label="基金概况">
            <div>
              <h4>基金概况</h4>
            </div>
            <el-form-item v-for="(item, index) in dynamicValidateForm" :key="index" class="item">
              <div style="display: flex;">
                <el-form-item label="标题" prop="title">
                  <el-input v-model="item.introTitle" placeholder="标题" style="width:300px;"></el-input>
                </el-form-item>
                <el-form-item style="padding-left:200px;">
                  <el-button @click.prevent="removeDomain(item)">删除</el-button>
                </el-form-item>
              </div>
              <el-form-item label="说明" prop="sort">
                <el-input
                  v-model="item.introDesc"
                  type="textarea"
                  rows="5"
                  style="width:500px;"
                  placeholder="说明"
                ></el-input>
              </el-form-item>
            </el-form-item>
            <div class="btn">
              <el-button type="primary" size="mini" @click="addDomain">+继续添加</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane label="资产分布">
            <div class="label-title">资产分布图文详情编辑</div>
            <div class="quill-wrap" style="height:350px;width:100%">
              <quill-editor
                style="height:300px;"
                v-model="temp.assetDesc "
                ref="myQuillEditor"
                :options="editorOption"
              ></quill-editor>
            </div>
          </el-tab-pane>
          <el-tab-pane label="销售文件">
            <div class="label-title">销售文件图文详情编辑</div>
            <div class="quill-wrap" style="height:350px;width:100%">
              <quill-editor
                style="height:300px;"
                v-model="temp.saleDocDesc "
                ref="myQuillEditor"
                :options="editorOption"
              ></quill-editor>
            </div>
          </el-tab-pane>
          <el-tab-pane label="交易规则">
            <div class="label-title">交易规则图文详情编辑</div>
            <div class="quill-wrap" style="height:350px;width:100%">
              <quill-editor
                style="height:300px;"
                v-model="temp.saleRuleDesc "
                ref="myQuillEditor"
                :options="editorOption"
              ></quill-editor>
            </div>
          </el-tab-pane>
          <el-tab-pane label="风险提示">
            <div class="label-title">风险提示图文详情编辑</div>
            <div class="quill-wrap" style="height:350px;width:100%">
              <quill-editor
                style="height:300px;"
                v-model="temp.riskDesc "
                ref="myQuillEditor"
                :options="editorOption"
              ></quill-editor>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
let statusFilter = ["否", "是"];
let projectFilter = [{ value: 1, title: "固定收益理财" }];
let statusType = {
  1: "待审核",
  5: "审核驳回",
  10: "初审核通过",
  20: "复审通过"
};
let manageFeeTypeFilter = { 1: "按融资比例收取", 2: "按固定金额收取" };
let statustagFilter = ["success", "danger", "info", "warning"];
let adPositiontagFilter = ["success", "danger", "info", "warning"];
let typeBanner = ["App轮播banner", "微信轮播banner", "首页banner"];
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor, Quill } from "vue-quill-editor";
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      dynamicValidateForm: [],
      recoValidateForm: [],
      tableHeight: 400,
      total: 0,
      container: false,
      list: [],
      roleList: [],
      checkStatusList: [
        {
          label: "待审核",
          value: 1
        },
        {
          label: "审核驳回",
          value: 5
        },
        {
          label: "初审核通过",
          value: 10
        },
        {
          label: "复审通过",
          value: 20
        }
      ],
      investMonthItem: [1, 3, 6, 9, 12],
      manageFeeTypeItems: [
        { value: 1, title: "按融资比例收取" },
        { value: 2, title: "按固定金额收取" }
      ],

      selectedDays: {
        "10": "10天",
        "20": "20天",
        "30": "30天"
      },
      editorOption: {
        placeholder: "在这里输入内容",
        modules: {}
      },
      params: {
        pageNo: 1,
        pageSize: 20
      },
      temp: {
        recommendDesc: "",
        saleDocDesc: "",
        status: "",
        coverImg: "",
        roleIdList: "",
        transferFlag: "",
        projectType: "",
        manageFeeType: "",
        introList: [],
        recoList: []
      },
      pickerOptions1: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      statusFilter: statusFilter,
      typeBanner: typeBanner,
      projectFilter: projectFilter,
      statusType: statusType,
      manageFeeTypeFilter: manageFeeTypeFilter,
      cityIdOptions: [],
      rules: {
        projectName: [
          {
            required: true,
            message: "项目名称",
            trigger: "change"
          }
        ],
        projectType: [
          { required: true, message: "项目类型", trigger: "change" }
        ],
        minLimitAmount: [
          { required: true, message: "最低投资额度", trigger: "change" }
        ],
        investMonth: [
          { required: true, message: "投资期限(月)", trigger: "change" }
        ],
        projectTag: [
          { required: true, message: "项目标签", trigger: "change" }
        ],
        manageFeeType: [
          { required: true, message: "管理费类型", trigger: "change" }
        ],
        totalInvestAmount: [
          { required: true, message: "投资总额", trigger: "change" }
        ],
        maxLimitAmount: [
          { required: true, message: "最高限额", trigger: "change" }
        ],
        planIncomeRate: [
          { required: true, message: "预计收益", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.loadData();
  },
  filters: {
    manageFeeTypeFilters(status) {
      return manageFeeTypeFilter[parseInt(status)];
    },
    statusFilter(status) {
      return statusFilter[parseInt(status)];
    },
    statusTypes(status) {
      return statusType[parseInt(status)];
    },
    projectFilter(status) {
      return projectFilter[parseInt(status-1)].title;
    },
    typeBanner(status) {
      return typeBanner[parseInt(status)];
    },
    statustagFilter(status) {
      return statustagFilter[parseInt(status)];
    },
    adPositiontagFilter(status) {
      return adPositiontagFilter[parseInt(status)];
    }
  },
  methods: {
    removeDomain(item) {
      var index = this.dynamicValidateForm.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.splice(index, 1);
      }
    },
    recoRemoveDomain(item) {
      var index = this.recoValidateForm.indexOf(item);
      if (index !== -1) {
        this.recoValidateForm.splice(index, 1);
      }
    },
    addDomain() {
      this.dynamicValidateForm.push({});
    },
    recoAddDomain() {
      this.recoValidateForm.push({});
    },
    handleFilter() {
      this.loadData();
    },
    changeEnable(item) {
      var status = item.status;
      if (status == 5) {
        status = 1;
      } else {
        status = 0;
      }
      this.$prompt("审核备注", "确认审核通过吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          this.$post("/admin/finance_project/check", {
            id: item.id,
            checkStatus: status,
            checkStep: 1,
            remark: value
          }).then(data => {
            this.loadData();
          });
        })
        .catch(() => {});
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.loadData();
    },
    handleCurrentChange(page) {
      this.params.pageNo = page;
      this.loadData();
    },
    handleDelete(row) {
      this.$confirm("确定删除该项目吗?", "提示").then(_ => {
        this.$post("/admin/finance_project/delete", {
          id: row.id
        }).then(data => {
          this.loadData();
        });
      });
    },
    handleDetail(row) {
      this.$confirm("详情", "提示").then(_ => {
        this.$post("/admin/finance_project/detail", {
          id: row.id
        }).then(data => {
          console.log(data);
        });
      });
    },
    editRow(row) {
      this.queryDetail(row.id, data => {
        this.temp = data;
        if (this.temp.introList) {
          this.dynamicValidateForm = [];
          this.temp.introList.forEach((el, index) => {
            this.dynamicValidateForm.push(el);
          });
        }
        if (this.temp.recoList) {
          this.recoValidateForm = [];
          this.temp.recoList.forEach((el, index) => {
            this.recoValidateForm.push(el); //把获取到的数据，遍历把所有数据添加到 recoValidateForm 变量中
          });
        }
        this.isEditing = true;
        this.dialogFormVisible = true;
      });
    },
    queryDetail(id, callback) {
      this.$post("/admin/finance_project/detail", { id }).then(data => {
        callback && callback(data);
      });
    },

    // editRow(row) {
    //   this.$post("/admin/finance_project/detail", {
    //     id: row.id
    //   }).then(data => {
    //   });
    //   this.dialogFormVisible = true;
    //   this.isEditing = true;
    //   this.temp = Object.assign({}, row);
    //   console.log(this.temp)
    // },
    submitFormAction() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.submiting = true;
          const postData = Object.assign({}, this.temp);
          this.dynamicValidateForm.forEach((el, idx) => {
            Object.keys(el).forEach(k => {
              postData["introList[" + idx + "]." + k] = el[k];
            });
          });
          this.recoValidateForm.forEach((el, idx) => {
            Object.keys(el).forEach(k => {
              postData["recoList[" + idx + "]." + k] = el[k];
            });
          });
          delete postData.introList;
          delete postData.recoList;
          let url = "";
          if (this.isEditing) {
            url = "/admin/finance_project/modify";
          }
          this.$post(url, postData)
            .then(data => {
              this.loadData();
              this.$$notify("操作成功");
              this.dialogFormVisible = false;
              this.temp = {};
            })
            .finally(_ => {
              this.submiting = false;
            });
        }
      });
    },
    loadData() {
      this.$post("/admin/finance_project/list", this.params)
        .then(data => {
          this.total = data.total;
          this.list = data.dataList;
        })
        .catch(_ => {
          console.log("Err", _);
        });
    }
    // exportExcelFile () {
    //   this.exportExcel({
    //     title: '广告管理',
    //     fields: [
    //       {
    //         field: 'title',
    //         title: '广告名称'
    //       },

    //       {
    //         field: 'sort',
    //         title: '顺序'
    //       },

    //       {
    //         field: 'startDate',
    //         title: '生效时间'
    //       },

    //       {
    //         field: 'endDate',
    //         title: '失效时间'
    //       },

    //       {
    //         field: 'status',
    //         title: '发布状态',
    //         valueMap: ['上线', '下线']
    //       },

    //       {
    //         field: 'createTime',
    //         title: '操作时间'
    //       },

    //       {
    //         field: 'linkAddr',
    //         title: '链接'
    //       },

    //       {
    //         field: 'cityName',
    //         title: '城市位置'
    //       },

    //       {
    //         field: 'adPosition',
    //         title: '广告位置',
    //         valueMap: ['首页底部', '首页顶部', '特价专区', '限时抢购（封面）', '限时抢购（活动页）']
    //       }
    //     ]
    //   }).then(info => {
    //     this.openWin(info)
    //   })
    // }
  }
};
</script>

<style scoped>
.avatar-uploader {
  width: 375px;
  height: 155px;
}

.avatar-uploader >>> .avatar {
  width: 375px;
  height: 155px;
}

.avatar-uploader >>> .avatar-uploader-icon {
  width: 375px;
  height: 155px;
}
.img-src {
  height: 100px;
}
</style>
